from helpers import updateInfo
from helpers import CompHelp
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
    """ Open competition page class """
    def get(self):
        user=users.get_current_user()
        
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        # Load user info from database
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
        
        template_values = {
            'maxTitleLength' : updateInfo.maxTitleLength, 
            'current_user_totalamount': current_user.totalamount,
            'current_user_bankamount': current_user.bankamount,
            'current_user_investamount': current_user.totalamount-current_user.bankamount,
            'logusername' : user.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'logintext' : 'Sign Out',
            'categoryName' : 'Open Competition',
            'setHead' : 1,
            'maincontent' : 'account_main.html',
            'headContent' : 'opencomp_head.html',
            'account_main_content' : 'opencomp_main.html'
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))

    def post(self):
 
        # Handle all forms submittions
        user=users.get_current_user()
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)

        if (self.request.get('action')=="opencompetition"):
        
            # Check for existing users
            emailList=self.request.get('inviteusers').splitlines()
            # Remove duplicates
            emailList=set(emailList)
            # Check for valid int competition amount
            try:
                compamount=int(self.request.get('amount'))
                startdate=int(self.request.get('startdate'))
                enddate=int(self.request.get('enddate'))
                owner = user
            except:
                self.redirect('/report?msg=5')
                return
            
            if self.request.get('title'):
                title=self.request.get('title')
            else:
                title="TrendSE Competition"
            competition, password=CompHelp.openComp(compamount, emailList, current_user, startdate, enddate, title, self.request.get('publiccomp'), None, 0, owner, 0)
            
            if competition==-1:
                self.redirect('/report?msg=8')
                return
            
            elif competition==-3:
                self.redirect('/report?msg=12')
                return
                
            elif CompHelp.joinCompetition(current_user,competition,0,'')!=1:
                self.redirect('/report?msg=9')   
                return
            
            self.redirect('/Competition?id=%s&PKey=%s' % (str(competition.key()),password))
            return
        
application = webapp.WSGIApplication(
                                     [('/openCompetition', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
